package file

import (
	"errors"
	"fmt"
	"io"
	"log"
	"os"
)

func CopyFiles(srcDir, dstDir string) {
	// Check if source directory exists
	srcInfo, err := os.Stat(srcDir)
	if err != nil {
		log.Fatal(err)
	}
	if !srcInfo.IsDir() {
		log.Fatal(errors.New(srcDir + " is not a directory"))
	}

	// Check if destination directory exists
	dstInfo, err := os.Stat(dstDir)
	if err != nil {
		log.Fatal(err)
	}
	if !dstInfo.IsDir() {
		log.Fatal(errors.New(dstDir + " is not a directory"))
	}

	// Read source directory entries
	srcEntries, err := os.ReadDir(srcDir)
	if err != nil {
		log.Fatal(err)
	}

	// Loop over source directory entries
	for _, srcEntry := range srcEntries {
		srcPath := srcDir + "/" + srcEntry.Name()
		dstPath := dstDir + "/" + srcEntry.Name()

		// Check if entry is a regular file
		srcFileStat, err := os.Stat(srcPath)
		if err != nil {
			log.Println(err)
			continue
		}
		if !srcFileStat.Mode().IsRegular() {
			log.Println(srcPath + " is not a regular file")
			continue
		}

		// Copy file content
		nBytes, err := copyFile(srcPath, dstPath)
		if err != nil {
			log.Println(err)
			continue
		}

		// Print result
		fmt.Printf("Copied %s to %s (%d bytes)\n", srcPath, dstPath, nBytes)
	}
}

// copyFile copies the contents of the source file to the destination file
func copyFile(src, dst string) (int64, error) {
	// Open source file for reading
	source, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer source.Close()

	// Create destination file for writing
	destination, err := os.Create(dst)
	if err != nil {
		return 0, err
	}
	defer destination.Close()

	// Copy source to destination
	nBytes, err := io.Copy(destination, source)
	return nBytes, err
}